XState 紹介とサンプルコード
XState は何ですか?
State machines and statecharts for the modern web.
皆さんは Vuex がよくわかるはず、vuexは state management pattern + library for Vue.js applications です。 そして、XState は state machine and statecharts です。
だから XState は vuex と少し違います。
vuex は主にcomponentsの間に state マネージメントする。
XState は主に state の変換をコントロールする。
statecharts は何ですか
https://gyazo.com/b164d5eb66e3c3a002b03976b18f8d02
off と on 二つの状態があります。
off + flick = on
on + flick = off
このような状態遷移を表現するグラフは statecharts です。
交差点の信号
https://gyazo.com/06375cbe031c64ab704dadf7d2269db7
緑→黄色→赤→緑(loop)
一般的なstate management には、如何開発する?
code:light logic
let light = 'green'
// change to yello
light = 'yello'
// change to red
light = 'red'
// change to green
light = 'green'
statechart state management には、如何開発する?
code:xstate
import { Machine } from 'xstate';
const lightMachine = Machine({
id: 'light',
initial: 'green',
states: {
green: {
on: {
TIMER: 'yellow'
}
},
yellow: {
on: {
TIMER: 'red'
}
},
red: {
on: {
TIMER: 'green'
}
}
}
});
const currentState = 'green';
const nextState = lightMachine.transition(currentState, 'TIMER').value;
// => 'yellow'
さらに複雑だと思いますか?
しかし、コードが複雑になるけど、状態の遷移が簡単になりました。
如何いうこと?
green, yello, red 三つの状態にはいくら状態遷移がありますか?
結果:9
この中に、正しい状態遷移はいくら?
結果:3
table:light
current/next green yello red
green x o x
yello x x o
red o x x
computer science は数学、物理学と同じ、ロジックが必要ですよ。
如何使う?
XState はUI framework を依存しない、だから何のUI framework でも使えます。
Vue の場合、一番簡単の使い方はVue composition API 利用して、useMachineを使います。
実際開発流れ
1. 機能理解して、UI/UX から statechart を描きます。
2. statechart export
3. XState action 実装
4. UI 開発
要望:
普通のフォームを実装、
APIからデータを取得して、画面に表示する。
データ更新して、APIに送信する。
1. UI
https://gyazo.com/97814a7db34582d6a897d0b434eef2a8
2. UX
https://gyazo.com/5dc7bbfe4f3fd639d7b5e0678567fcd9
3. statechart
code:statechart
{
"initial": "idle",
"states": {
"idle": {
"on": {
"fetch": "fetching"
}
},
"fetching": {
"on": {
"onError": "fetchFailed",
"onDone": "normal"
}
},
"fetchFailed": {
"id": "e1395b96"
},
"normal": {
"on": {
"onSubmit": "updating"
}
},
"updating": {
"on": {
"onError": "updateFailure",
"onDone": "normal"
}
},
"updateFailure": {
"on": {
"ok": "normal"
}
}
},
}
4. Xstate action
code:xstate
initial: 'idle',
states: {
idle: {
on: {
fetch: 'fetching',
},
},
fetching: {
invoke: {
id: 'fetchData',
src: 'fetchData',
onDone: {
target: 'normal',
},
onError: {
target: 'fetchFailed',
},
},
},
fetchFailed: {},
normal: {
on: {
onSubmit: 'updating',
},
},
updating: {
invoke: {
id: 'updateData',
src: 'updateData',
onDone: {
target: 'normal',
},
onError: {
target: 'updateFailed',
},
},
},
updateFailed: {
on: {
ok: 'normal',
},
},
},
source code:
Preview:
API が必要から、まだdeployしてない。
source code に API code がある、心配しないでください。
links
https://gyazo.com/1cf14c1af218be94c3a6e31e7e0e810f
上妻: よく理解できました、ありがとうございます!これはECのカートを実装するときに便利かもしれないです。あらゆるフレームワークにこのようなstateライブラリはありますが、stateをnextする時のvalidationの実装が目的だったりしますよね。
tj.icon はい、そのuse case もありますね。
👍 onuma onuma.icon がいいねしました on 2020/6/6